package com.breeze.jetpackproject.viewmodel;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.breeze.jetpackproject.R;

public class Demo2Activity extends AppCompatActivity {
    private static final String TAG = "Demo2Activity";
    private Demo2ViewModel demo2ViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo2);
        // 1. 这种创建方式，每次onCreate都会创建一个实例，导致实例在无法在Activity重新创建时复用，也会导致数据重新加载耗时
        // demo2ViewModel = new Demo2ViewModel();
        // 2. 已被废弃
        // demo2ViewModel = ViewModelProviders.of(this).get(Demo2ViewModel.class);
        // 3. 可以复用ViewModel，Activity在转屏重新创建时会直接通知观察者缓存的值
        demo2ViewModel = new ViewModelProvider(this).get(Demo2ViewModel.class);
        this.demo2ViewModel.getName().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.i(TAG, "onChanged: loadName=" + s);
            }
        });
    }
}